﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Model;
using DAL;
using CommonUtility;
using System.Web.Script.Serialization;
using System.Data.SqlClient;
using System.Data;
namespace BLL
{
    public class bllFunction
    {
        public string LoadFunItem(UserInfo _operator)
        {
            string result = "";
            try
            {
                IList<ActionInfo> list = DAL.Action.GetList(" flag='A' ");
                IList<clsSelect> listS = new List<clsSelect>();
                foreach (ActionInfo act in list)
                {
                    clsSelect clsS = new clsSelect();
                    clsS.id = act.ActID;
                    clsS.value = act.ActName;
                    clsS.text = act.ActName;
                    listS.Add(clsS);
                }
                string json = new JavaScriptSerializer().Serialize(listS);
                result = json;
            }
            catch (Exception ex)
            {
                result = "ERR";
                Common.Application_Error_Server("Functioninf.aspx.cs/loadFunData() " + _operator.Name, ex);
            }

            return result;
        }
        /// <summary>
        /// 根据funID和funDesc获取所有Function
        /// </summary>
        /// <param name="funID"></param>
        /// <param name="funDesc"></param>
        /// <param name="_operator"></param>
        /// <returns></returns>
        public string GetFunInf(string funID, string funDesc, UserInfo _operator)
        {
            string strSQL = "1=1";
            SqlParameter[] paras = null;
            IList<SqlParameter> paraList = new List<SqlParameter>();

            if (!string.IsNullOrEmpty(funID))
            {
                strSQL += " and funID like '%'+@funID+'%'";
                paraList.Add(new SqlParameter("@funID", SqlDbType.NVarChar, 20) { Value = "%" + funID + "%" });
            }
            if (!string.IsNullOrEmpty(funDesc))
            {
                strSQL += " and funDesc like '%'+@funDesc+'%'";
                paraList.Add(new SqlParameter("@funDesc", SqlDbType.NVarChar, 40) { Value = "%" + funDesc + "%" });
            }
            if (paraList.Count > 0)
            {
                paras = paraList.ToArray();
            }

            string result = "";
            try
            {
                IList<FunctionInfo> list = new List<FunctionInfo>();
                list = Function.GetList(strSQL, paras);
                int j = 0;
                StringBuilder strAppend = new StringBuilder();
                strAppend.Append("[");
                foreach (FunctionInfo fun in list)
                {
                    string actDesc = FunctionAction.GetActDesc(fun.FunID);
                    string actID = FunctionAction.GetActID(fun.FunID);
                    strAppend.Append("{");
                    strAppend.Append("\"RID\":" + fun.RID + ",");
                    strAppend.Append("\"FunID\":\"" + fun.FunID + "\",");
                    strAppend.Append("\"FunDesc\":\"" + fun.FunDesc + "\",");
                    strAppend.Append("\"ActDesc\":\"" + actDesc + "\",");
                    strAppend.Append("\"ActID\":\"" + actID + "\",");
                    strAppend.Append("\"Flag\":\"" + fun.Flag + "\",");
                    strAppend.Append("\"Lpt\":\"" + fun.Lpt + "\",");
                    strAppend.Append("\"Whom\":\"" + fun.Whom + "\"");
                    strAppend.Append("}");
                    if (j < list.Count - 1)
                        strAppend.Append(",");
                    j++;
                }
                strAppend.Append("]");
                string json = strAppend.ToString();
                result = @"{""Rows"":" + json + @",""Total"":""" + list.Count + @"""}";
            }
            catch (Exception ex)
            {
                result = ex.Message;
                Common.Application_Error_Server("bllFunction.cs/LoadList(" + strSQL + ") " + _operator.Name, ex);
            }
            return result;
        }




        /// <summary>
        /// 新增或保存
        /// </summary>
        /// <param name="_funID"></param>
        /// <param name="rid"></param>
        /// <param name="funID"></param>
        /// <param name="funDesc"></param>
        /// <param name="flag"></param>
        /// <param name="actID"></param>
        /// <param name="_operator"></param>
        /// <returns></returns>
        public string Save(string _funID, string rid, string funID, string funDesc, string flag,string actID, UserInfo _operator)
        {
            string result = string.Empty;
            System.Data.SqlClient.SqlTransaction myTran = SQLCommon.GetSqlTransaction();
            System.Data.SqlClient.SqlConnection myConn = myTran.Connection;
            try
            {
                

                if (string.IsNullOrEmpty(rid))
                {
                    //新增
                    if (DAL.Function.Count(" funID='" + funID + "'") > 0)
                    {
                        return "existed";
                    }
                    else
                    {
                        Model.FunctionInfo model = new FunctionInfo();
                        model.FunID = funID;
                        model.FunDesc = funDesc;
                        model.Flag = flag;
                        model.Lpt = DateTime.Now.ToString();
                        model.Whom = _operator.UserID;
                        DAL.Function.Add(model, myTran);
                        BLL.bllLog.AddLog(_funID, "Add", model.FunID + ":" + model.FunDesc, _operator.UserID, myTran);
                    }
                }
                else
                {
                    //修改
                    //如果是修改先删除t_FunActInf表记录
                    var functionActionList = DAL.FunctionAction.GetList(" funID='" + funID + "'");
                    foreach (var functionAction in functionActionList)
                    {
                        DAL.FunctionAction.Delete(functionAction, myTran);
                    }

                    
                    //修改Function
                    Model.FunctionInfo model = new FunctionInfo();
                    model.RID = Common.ToInt32(rid);
                    model.FunID = funID;
                    model.FunDesc = funDesc;
                    model.Flag = flag;
                    model.Lpt = DateTime.Now.ToString();
                    model.Whom = _operator.UserID;
                    DAL.Function.Edit(model, myTran);
                    BLL.bllLog.AddLog(_funID, "Edit", model.FunID + ":" + model.FunDesc, _operator.UserID, myTran);
                }

                //t_FunActInf添加勾选的action
                if (!string.IsNullOrEmpty(actID.Trim()))
                {
                    string[] arrayActID = actID.Split('/');
                    foreach (var id in arrayActID)
                    {
                        var funAct = new FunctionActionInfo();
                        funAct.ActID = id;
                        funAct.FunID = funID.Trim();
                        DAL.FunctionAction.Add(funAct, myTran);
                    }
                }

                myTran.Commit();

                //匹配tRolePermission表中的记录，如果在t_FunActInf不存在对应的tRolePermission中的funID和actID，则这些记录也被删除
                var faList = DAL.FunctionAction.GetList(" funID='" + funID + "'");
                if (faList.ToList().Count > 0)
                {
                    var actIDS = string.Join(",", faList.Select(i => "'" + i.ActID + "'").ToList().ToArray());
                    var needDelete = DAL.RolePermission.GetList(" funID='" + funID + "' and actID not in (" + actIDS + ")");
                    foreach (var rolePermission in needDelete)
                    {
                        DAL.RolePermission.Delete(rolePermission);
                    }
                }
                else
                {
                    //t_FunActInf对应funID的actID为空，则tRolePermission对应也要清空
                    var needDelete = DAL.RolePermission.GetList(" funID='" + funID + "'");
                    foreach (var rolePermission in needDelete)
                    {
                        DAL.RolePermission.Delete(rolePermission);
                    }
                }
                
            }
            catch (Exception ex)
            {
                result = ex.Message;
                myTran.Rollback();
                Common.Application_Error_Server("BLL/bllFunction.cs/Save()" + _operator.Name, ex);
            }
            finally
            {
                myConn.Close();
                myTran.Dispose();
                myConn.Dispose();
            }
            return result;
        }

        /// <summary>
        /// 获取FunDesc
        /// </summary>
        /// <param name="_FunID"></param>
        /// <returns></returns>
        public static string GetFunDesc(string _FunID)
        {
            string res = string.Empty;
            try
            {
                IList<FunctionInfo> list = DAL.Function.GetList(" FunID = '" + _FunID + "'");
                if (list.Count > 0)
                {
                    res = string.Join(",", list.Select(d => d.FunDesc).ToArray());
                }
                else
                {
                    res = _FunID;
                }
            }
            catch (Exception ex)
            {
                Common.Application_Error_Server("bllFunction.cs/GetFunDesc(" + _FunID + ")", ex);
            }
            return res;
        }

        /// <summary>
        /// 设置是否有效
        /// </summary>
        /// <param name="funID"></param>
        /// <param name="rids"></param>
        /// <param name="flag">C016 OR C017</param>
        /// <param name="_oUser"></param>
        /// <returns></returns>
        public string Process(string funID, string rids, string flag, UserInfo _operator)
        {
            string result = string.Empty;
            System.Data.SqlClient.SqlTransaction myTran = SQLCommon.GetSqlTransaction();
            System.Data.SqlClient.SqlConnection myConn = myTran.Connection;
            try
            {
                IList<FunctionInfo> list = Function.GetList(" RID in (" + rids + ")");
                var funids = string.Join(",", list.Select(d => d.FunID).ToArray());
                foreach (var funinfo in list)
                {
                    funinfo.Flag = flag;
                    funinfo.Whom = _operator.UserID;
                    Function.Edit(funinfo, myTran);
                }
                //添加操作记录
                var action = flag == "A" ? "Active" : "Inactive";
                BLL.bllLog.AddLog(funID, action, funids, _operator.UserID, myTran);
                myTran.Commit();
            }
            catch (Exception ex)
            {
                result = ex.Message;
                myTran.Rollback();
                Common.Application_Error_Server("bllFunction.cs/Process(" + rids + ") " + _operator.Name, ex);
            }
            finally
            {
                myConn.Close();
                myTran.Dispose();
                myConn.Dispose();
            }

            return result;
        }
    }
}
